﻿using System;
using System.IO;

namespace ooWii.Security
{
	public class Signature
	{
		#region Signature

		public static Signature Create( Stream stream )
		{
			byte[] signatureTypeBuffer = new byte[ 4 ];
			if( stream.Read( signatureTypeBuffer, 0, signatureTypeBuffer.Length ) != 4 )
			{
				throw new WiiException( "error reading signature type" );
			}

			SignatureType signatureType = (SignatureType)WiiBuffer.GetUInt32( signatureTypeBuffer, 0 );

			byte[] bytes = new byte[ getSignatureLength( signatureType ) ];
			if( stream.Read( bytes, 0, bytes.Length ) != bytes.Length )
			{
				throw new WiiException( "error reading signature" );
			}

			stream.Position = WiiBuffer.Align( stream.Position, 64 );

			return new Signature( signatureType, bytes );
		}

		static int getSignatureLength( SignatureType signatureType )
		{
			switch( signatureType )
			{
			case SignatureType.RSA4096:
				return 0x200;

			case SignatureType.RSA2048:
				return 0x100;

			case SignatureType.ElipticCurve:
				return 0x40;

			default:
				throw new WiiException( string.Format( "Invalid SignatureType {0}", signatureType ) );
			}
		}

		SignatureType type;
		byte[] bytes;

		Signature( SignatureType type, byte[] bytes )
		{
			this.type = type;
			this.bytes = bytes;
		}

		public SignatureType Type
		{
			get
			{
				return type;
			}
		}

		public byte[] Bytes
		{
			get
			{
				return bytes;
			}
		}

		#endregion
	}
}
